<!-- 分类设置 -->
<template>
  <div>
    <a-button
      v-if="!(type === 1 && dataList.length >= 5)"
      type="primary"
      :disabled="(type === 0 && dataList.length >= 16) || (type === 2 && dataList.length >= 8)"
      @click="handleAdd"
      style="margin-bottom: 10px"
      >添加
    </a-button>
    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      :pageSize="(type === 5 && 50) || 10"
    >
      <template v-if="dataList[index]" slot="name" slot-scope="text, record, index">
        <a-input v-if="dataList[index].editable" style="width: 200px" v-model="record.name" />
        <template v-else>
          {{ text }}
        </template>
      </template>
      <template v-if="dataList[index]" slot="desc" slot-scope="text, record, index">
        <a-input v-if="dataList[index].editable" v-model="record.desc" />
        <template v-else>
          {{ text }}
        </template>
      </template>
      <template v-if="dataList[index]" slot="icon" slot-scope="text, record, index">
        <template v-if="type === 1">
          <span
            v-if="dataList[index].editable"
            :class="['ant-iconfont', 'icon-' + (text && text.indexOf('http') === -1 ? text : 'plus')]"
            style="font-size: 36px"
            @click="iconselect(record.id)"
          ></span>
          <span
            v-else
            :class="['ant-iconfont', 'icon-' + (text && text.indexOf('http') === -1 ? text : 'plus')]"
            style="font-size: 36px; opacity: 0.6"
          ></span>
        </template>

        <template v-else>
          <!-- 小程序配置-分类设置 type = 0 -->
          <!-- 小程序配置-分组设置 type = 5 -->
          <UploadImg
            v-model="record.iconUrl"
            :disabled="!dataList[index].editable"
            :width="type === 0 ? 100 : 172"
            :height="100"
            warehouse
            cropper
            :cropperEnlarge="1"
            :isShowTip="false"
          >
            <template #tips>
              {{ type === 0 ? '100*100' : '344*200' }}
            </template>
          </UploadImg>
        </template>
      </template>
      <template v-if="dataList[index]" slot="type" slot-scope="text, record, index">
        <a-select
          v-model="dataList[index].typeOptionsId"
          style="width: 120px"
          @change="val => handleChangeType(val, record, index)"
          :disabled="(type === 1 && (index === 0 || index === dataList.length - 1)) || !dataList[index].editable"
        >
          <a-select-option v-for="item in sysOptions" :value="item.id" :key="item.id"
            >{{ item.optionsName }}
          </a-select-option>
        </a-select>
      </template>
      <template v-if="dataList[index]" slot="link" slot-scope="text, record, index">
        <!-- 资讯分类 -->
        <a-cascader
          v-if="dataList[index].typeOptionsId === 1"
          changeOnSelect
          :fieldNames="{ label: 'module', value: 'id', children: 'children' }"
          :options="managementTypeList"
          :default-value="[(dataList[index].optionsId || '').split('/').map(m => Number(m))]"
          style="margin-left: 10px"
          @change="(val, option) => handleCascaderChange(val, option, index)"
          placeholder="请选择"
          :disabled="!dataList[index].editable"
        />

        <!-- 系统链接 -->
        <a-select
          v-else-if="dataList[index].typeOptionsId === 4"
          :value="dataList[index].optionsId ? Number(dataList[index].optionsId) : undefined"
          style="width: 200px; margin-left: 10px"
          :disabled="(type === 1 && (index === 0 || index === dataList.length - 1)) || !dataList[index].editable"
          @change="value => handleChangeLink(value, index)"
        >
          <a-select-option
            v-for="option in linkList"
            :value="option.id"
            :key="option.id"
            :disabled="option.linkUrl === 'home' || option.linkUrl === 'mine'"
            >{{ option.name }}
          </a-select-option>
        </a-select>

        <template
          v-else-if="
            dataList[index].typeOptionsId === 6 ||
              dataList[index].typeOptionsId === 7 ||
              dataList[index].typeOptionsId === 11
          "
        >
          <a-input
            v-if="dataList[index].editable"
            v-model="record.linkUrl"
            :placeholder="
              { 6: '请输入小程序路径', 7: '请输入配置的业务域名，例：https://xxx.com', 11: '请输入站内链接地址' }[
                dataList[index].typeOptionsId
              ]
            "
          />
          <template v-else>
            {{ record.linkUrl }}
          </template>
        </template>
        <template v-else-if="dataList[index].typeOptionsId === 10 || dataList[index].typeOptionsId === 12"></template>
        <!-- 资讯列表/活动列表/相册列表 -->
        <a-select
          v-else
          :value="
            !dataList[index].optionsId || dataList[index].optionsId.indexOf('/') != -1
              ? undefined
              : Number(dataList[index].optionsId)
          "
          :show-search="true"
          :default-active-first-option="false"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
          :disabled="
            dataList[index].typeOptionsId === 8 || dataList[index].typeOptionsId === 9 || !dataList[index].editable
          "
          style="width: 200px; margin-left: 10px"
          :placeholder="
            dataList[index].typeOptionsId === 8
              ? '活动列表'
              : dataList[index].typeOptionsId === 9
              ? '相册列表'
              : '请输入标题搜索'
          "
          @search="val => handleSearchOps(val, dataList[index].typeOptionsId)"
          @change="value => handleChangeOps(value, dataList[index], index)"
        >
          <a-select-option
            v-for="option in dataList[index].typeOptionsId === 2
              ? managementList
              : dataList[index].typeOptionsId === 3
              ? activityList
              : photoAlbumList"
            :value="option.id"
            :key="option.id"
            >{{ option.title || option.name }}
          </a-select-option>
        </a-select>
        <!-- </template> -->
      </template>
      <template v-if="dataList[index]" slot="appId" slot-scope="text, record, index">
        <template v-if="dataList[index].typeOptionsId === 6">
          <a-input v-if="dataList[index].editable" v-model="record.appId" placeholder="请输入小程序appid" />
          <template v-else>
            {{ record.appId }}
          </template>
        </template>
      </template>
      <template v-if="dataList[index]" slot="iconUrl" slot-scope="text, record, index">
        <!-- PC官网配置-导航菜单 type = 2 -->
        <UploadImg
          v-model="record.iconUrl"
          :disabled="!dataList[index].editable"
          :width="192"
          :height="60"
          warehouse
          cropper
          :cropperEnlarge="4.8"
          :isShowTip="false"
        >
          <template #tips> 1920*600 </template>
        </UploadImg>
      </template>
      <template v-if="dataList[index]" slot="action" slot-scope="text, record, index">
        <div class="disFlxAC">
          <div class="editable-row-operations _mr-10">
            <span v-if="dataList[index].editable">
              <a @click="save(record.id)" class="_mr-10">保存</a>
              <a-popconfirm title="确定取消?" @confirm="cancel(record.id)">
                <a>取消</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="edit(record.id)">编辑</a>
            </span>
          </div>
          <a-button
            v-if="!(type == 1 && [1, 5].includes(record.sort))"
            type="primary"
            ghost
            size="small"
            class="_mr-5"
            @click="handleDel(record.id)"
          >
            删除
          </a-button>
          <template v-if="type == 1">
            <span v-if="isShowUp(index)">
              <a-divider type="vertical" />
              <a-icon type="arrow-up" @click="handleMove([record.id, dataList[index - 1].id])" />
            </span>
            <span v-if="isShowDown(index)">
              <a-divider type="vertical" />
              <a-icon type="arrow-down" @click="handleMove([record.id, dataList[index + 1].id])" />
            </span>
          </template>
          <template v-else>
            <span v-if="index > 0">
              <a-divider type="vertical" />
              <a-icon type="arrow-up" @click="handleMove([record.id, dataList[index - 1].id])" />
            </span>
            <span v-if="index < dataList.length - 1">
              <a-divider type="vertical" />
              <a-icon type="arrow-down" @click="handleMove([record.id, dataList[index + 1].id])" />
            </span>
          </template>
        </div>
      </template>
    </s-table>
    <IconSelectorModal ref="iconModal" @ok="setIcon" />
  </div>
</template>

<script>
import { STable } from '@/components'
import {
  configAppBasisDataList,
  getSysOptions,
  getSysOptionsById,
  addConfigAppBasisData,
  editConfigAppBasisData,
  delConfigAppBasisData,
  configAppBasisDataSwap,
  systemLinkList
} from '@/api/web/web'
import { consultGetList } from '@/api/content/management'
import { activityList } from '@/api/activity/activity'
import { photoAlbum } from '@/api/content/operate'
import IconSelectorModal from '@/components/IconSelectorModal/IconSelectorModal.vue'
import EditableCell from '@/components/EditableCell'
import UploadImg from '@/components/UpFile/uploadImg'

export default {
  //type: 0:小程序分类设置，1：小程序底部菜单栏配置，2：官网导航菜单, 5: 小程序分组设置
  props: ['type', 'selectType'],
  components: {
    STable,
    EditableCell,
    IconSelectorModal,
    UploadImg
  },
  data() {
    return {
      pageNum: 1,
      // 表头
      columns: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log('parameter---->', parameter)
        var params = {
          current: parameter.pageNum,
          size: parameter.pageSize
        }
        // this.listLoading = true;
        return configAppBasisDataList(Object.assign(params, { type: this.type }))
          .then(res => {
            this.listLoading = false
            if (res.code === 0) {
              this.pageNum = parameter.pageNum
              this.dataList = res.data.records || []
              // this.cacheData = this.dataList.map((item) => ({ ...item }))
              this.dataList.map(item => {
                if (item.typeOptionsId === 2) {
                  if (this.managementList.findIndex(f => f.id == item.optionsId) != -1) return
                  this.managementList.push({
                    id: Number(item.optionsId),
                    title: item.optionsName
                  })
                } else if (item.typeOptionsId === 3) {
                  if (this.activityList.findIndex(f => f.id == item.optionsId) != -1) return
                  this.activityList.push({
                    id: Number(item.optionsId),
                    title: item.optionsName
                  })
                } else if (item.typeOptionsId === 5) {
                  if (this.photoAlbumList.findIndex(f => f.id == item.optionsId) != -1) return
                  this.photoAlbumList.push({
                    id: Number(item.optionsId),
                    name: item.optionsName
                  })
                }
              })
              return res
            } else {
              this.$message.error(res.msg)
            }
          })
          .catch(err => {
            // this.listLoading = false;
            this.$message.error(err.msg)
          })
      },
      dataList: [],
      sysOptions: [],
      // level2SysOptions: [],
      form: {
        iconUrl: undefined,
        name: undefined,
        optionsId: undefined,
        optionsName: undefined,
        type: undefined,
        typeOptionsId: undefined,
        typeOptionsName: undefined
      },
      managementTypeList: [], //咨询分类列表
      managementList: [], //咨询列表
      activityList: [], //活动列表
      photoAlbumList: [], //相册列表
      linkList: [], //系统链接列表
      iconSet: {
        id: undefined
      },
      editingKey: undefined,
      targetCache: {}
    }
  },
  computed: {},
  watch: {},
  methods: {
    isShowUp(index) {
      if (!this.dataList[index - 1]) return false
      if (this.dataList[index - 1].sort == 1) return false
      if (this.dataList[index].sort == 5) return false
      return true
    },
    isShowDown(index) {
      if (!this.dataList[index + 1]) return false
      if (this.dataList[index + 1].sort == 5) return false
      if (this.dataList[index].sort == 1) return false
      return true
    },
    findMissingNumbers(arr) {
      arr.sort((a, b) => a - b)
      const missingNumbers = []
      for (let i = 0; i < arr.length - 1; i++) {
        const current = arr[i]
        const next = arr[i + 1]

        if (next - current > 1) {
          for (let j = current + 1; j < next; j++) {
            missingNumbers.push(j)
          }
        }
      }
      return missingNumbers
    },
    async get_sys_options() {
      let res = await getSysOptions({ type: this.selectType })
      this.sysOptions = res.data || []
    },
    handleChangeType(val, record, index) {
      const newData = [...this.dataList]
      const target = newData[index]
      if (target) {
        target.optionsId = ''
        target.linkUrl = ''
        target.appId = ''
        this.dataList = newData
      }
    },
    async get_sysOptionsById() {
      let res = await getSysOptionsById(1)
      this.managementTypeList = res.data || []
    },
    //获取系统链接
    async getSystemLinkList() {
      let type = 1
      if (this.type === 2) type = 2
      else if (this.type === 1) type = 0
      let res = await systemLinkList({ type })
      this.linkList = res.data || []
    },
    //更改系统链接选项
    handleChangeLink(value, index) {
      const newData = [...this.dataList]
      const target = newData[index]
      if (target) {
        target.optionsId = value
        target.linkUrl = this.linkList.find(f => f.id === value).linkUrl
        this.dataList = newData
      }
    },
    handleCascaderChange(val, option, index) {
      const newData = [...this.dataList]
      const target = newData[index]
      if (target) {
        target.optionsId = val.join('/')
        target.optionsName = option[option.length - 1].module
        this.dataList = newData
      }
    },
    async handleSearchOps(value, typeOptionsId) {
      if (typeOptionsId === 2) {
        let res = await consultGetList({
          current: 1,
          size: 10,
          title: value
        })
        this.managementList = res.data.records
      } else if (typeOptionsId === 3) {
        let res = await activityList({
          current: 1,
          pageSize: 10,
          title: value
        })
        this.activityList = res.data.records
      } else if (typeOptionsId === 5) {
        let res = await photoAlbum({
          current: 1,
          pageSize: 100,
          keyWord: value
        })
        this.photoAlbumList = res.data.records
      }
    },
    handleChangeOps(value, row, index) {
      if (this.type === 1) {
        if (this.dataList.findIndex(f => f.linkUrl === value) != -1) {
          return this.$message.error('默认链接不可重复选择')
        }

        const newData = [...this.dataList]
        const target = newData[index]
        if (target) {
          target.linkUrl = value
          this.dataList = newData
        }
      } else {
        let { id, name, typeOptionsId, typeOptionsName, iconUrl, sort } = row
        let option = (typeOptionsId === 2
          ? this.managementList
          : typeOptionsId === 3
          ? this.activityList
          : this.photoAlbumList
        ).find(f => f.id === value)

        const newData = [...this.dataList]
        const target = newData[index]
        if (target) {
          target.optionsId = value.toString()
          target.optionsName = typeOptionsId === 2 || typeOptionsId === 3 ? option.title : option.name
          this.dataList = newData
          console.log('this.dataList--->', this.dataList)
        }
      }
    },
    async handleUpdateType(row) {
      let res = {}
      if (row.id) {
        res = await editConfigAppBasisData({ ...row, type: this.type })
      } else {
        let sort = undefined
        const newSort = this.findMissingNumbers(this.dataList.map(item => item.sort))
        if (newSort.length && this.type == 1) {
          sort = newSort[0]
        }
        res = await addConfigAppBasisData({ ...row, type: this.type, sort })
      }
      let { code, msg } = res
      this.$message[code === 0 ? 'success' : 'error'](msg)
      if (code === 0) {
        this.$refs.table.refresh()
      }
    },
    onCellChange(id, sort, name) {
      this.handleUpdateType({ id, sort, name })
    },
    onDescChange(id, sort, desc) {
      this.handleUpdateType({ id, sort, desc })
    },
    onOutsideChange(row, linkUrl) {
      let { id, typeOptionsId } = row
      this.handleUpdateType({ id, typeOptionsId, linkUrl })
    },
    onAppIdChange(row, appId) {
      let { id, typeOptionsId } = row
      this.handleUpdateType({ id, typeOptionsId, appId })
    },
    //删除分类
    handleDel(id) {
      var _this = this
      this.$confirm({
        title: '删除?',
        content: '是否确定删除该数据?',
        onOk: async () => {
          let { code, msg } = await delConfigAppBasisData(id)
          _this.$message[code === 0 ? 'success' : 'error'](msg)
          if (code === 0) {
            _this.$refs.table.refresh()
          }
        },
        onCancel() {}
      })
    },
    //添加分类
    handleAdd() {
      this.handleUpdateType({})
    },
    async handleMove(ids) {
      let { code, msg } = await configAppBasisDataSwap(ids)
      this.$message[code === 0 ? 'success' : 'error'](msg)
      if (code === 0) {
        this.$refs.table.refresh()
      }
    },
    iconselect(id) {
      this.iconSet.id = id
      this.$refs.iconModal.show()
    },
    emitEmpty() {},
    setIcon(iconUrl) {
      const newData = [...this.dataList]
      const target = newData.find(item => this.iconSet.id === item.id)
      if (target) {
        target.iconUrl = iconUrl
        this.dataList = newData
      }
    },
    save(id) {
      let index = this.dataList.findIndex(item => id === item.id)
      let target = this.dataList[index]
      if (target) {
        let { name, iconUrl, typeOptionsId, optionsId, linkUrl, appId } = target
        if (!name || !iconUrl || !typeOptionsId) {
          return this.$message.warning('请完善数据后再保存！')
        }

        if ([6, 7, 8, 9, 11].includes(typeOptionsId)) {
          if ((typeOptionsId === 6 || typeOptionsId === 7) && !linkUrl) {
            return this.$message.warning('请完善数据后再保存！')
          }

          if (typeOptionsId === 6 && !appId) {
            return this.$message.warning('请完善数据后再保存！')
          }
        } else if (!optionsId && typeOptionsId !== 10 && typeOptionsId !== 12) {
          return this.$message.warning('请完善数据后再保存！')
        }

        this.handleUpdateType({
          ...target
        })
      }
      this.editingKey = ''
    },
    cancel(id) {
      let index = this.dataList.findIndex(item => id === item.id)
      let target = this.dataList[index]
      this.editingKey = ''
      if (target) {
        target = {
          ...target,
          ...this.targetCache[id],
          editable: false
        }
        this.dataList.splice(index, 1, target)
      }
    },
    edit(id) {
      let index = this.dataList.findIndex(item => id === item.id)
      let target = this.dataList[index]
      this.targetCache[id] = { ...target }
      this.editingKey = id
      if (target) {
        target.editable = true
        this.dataList.splice(index, 1, target)
      }
    },
    handleChange() {}
  },
  created() {
    this.get_sys_options()
    if (this.type != 1) {
      this.get_sysOptionsById()
      // this.getSystemLinkList()
    }
    this.getSystemLinkList()
    this.columns = [
      {
        title: '名称',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' },
        width: 260
      },
      {
        title: '图标',
        dataIndex: 'iconUrl',
        scopedSlots: { customRender: 'icon' },
        width: 180
      },
      {
        title: '类型',
        dataIndex: 'typeOptionsId',
        scopedSlots: { customRender: 'type' },
        width: 150
      },
      {
        title: '默认链接',
        dataIndex: 'optionsId',
        scopedSlots: { customRender: 'link' },
        width: 240
      },
      {
        title: 'Appid',
        dataIndex: 'appId',
        scopedSlots: { customRender: 'appId' },
        width: 200
      },
      {
        title: '排序',
        dataIndex: 'sort',
        width: 100
      }
    ]
    /**
     * 0: 分类设置
     * 1：底部菜单栏
     * 2：PC官网导航菜单
     * 5：分组设置
     */
    if (this.type === 0 || this.type === 1 || this.type === 5) {
      this.columns.push({
        title: '操作',
        scopedSlots: { customRender: 'action' },
        width: 180
      })
    } else if (this.type === 2) {
      this.columns = [
        {
          title: '名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '链接类型',
          dataIndex: 'typeOptionsId',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '选择数据',
          dataIndex: 'optionsId',
          scopedSlots: { customRender: 'link' }
        },
        {
          title: '背景图（宽高1920*600）',
          dataIndex: 'iconUrl',
          scopedSlots: { customRender: 'iconUrl' }
        },
        {
          title: '排序',
          dataIndex: 'sort'
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' },
          width: 180
        }
      ]
    }
    if (this.type === 5) {
      this.columns.splice(0, 1, {
        title: '标题',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' },
        width: 220
      })
      this.columns.splice(1, 1, {
        title: '图标（宽高分辨率344*200）',
        dataIndex: 'iconUrl',
        scopedSlots: { customRender: 'icon' },
        width: 220
      })
      this.columns.splice(1, 0, {
        title: '副标题',
        dataIndex: 'desc',
        scopedSlots: { customRender: 'desc' },
        width: 220
      })
    }
  },
  mounted() {}
}
</script>
<style scoped lang="less">
::v-deep {
  .ant-upload-picture-card-wrapper {
    width: unset !important;
  }
}
</style>
